package com.black.common.auth;

import java.util.Map;

/**
 * @author linwenfeng
 */
public class UserContextHolder {

    private static final ThreadLocal<Map<String, String>> CONTEXT = new ThreadLocal<>();

    public static void setContext(Map<String, String> userInfo) {
        CONTEXT.set(userInfo);
    }

    public static String getUsernameWithDefault() {
        String username = getUsername();
        return username == null ? "ADMIN" : username;
    }

    public static Long getUserIdWithDefault() {
        Long userId = getUserId();
        return userId == null ? 0 : userId;
    }

    public static String getUsername() {
        if (CONTEXT.get() == null) {
            return null;
        }
        return CONTEXT.get().get("username");
    }

    public static Long getUserId() {
        if (CONTEXT.get() == null || CONTEXT.get().get("userId") == null) {
            return null;
        }
        return Long.parseLong(CONTEXT.get().get("userId"));
    }

    public static String getComCode() {
        if (CONTEXT.get() == null) {
            return null;
        }
        return CONTEXT.get().get("comCode");
    }

    public static String getMainComCode() {
        if (CONTEXT.get() == null) {
            return null;
        }
        String comCode = CONTEXT.get().get("comCode");
        if (comCode != null) {
            return comCode.split("_")[0];
        }
        return null;
    }

    public static String getIconUrl() {
        if (CONTEXT.get() == null) {
            return null;
        }
        return CONTEXT.get().get("iconUrl");
    }

    public static void shutdown() {
        CONTEXT.remove();
    }
}
